#pragma once
#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>
#include "Mutex.hpp"
#include "Cond.hpp"

const int defaultcap = 5;

using namespace MutexMouble;
using namespace CondMoule;

template <class T>
class BlockQueue
{
private:
    bool IsFull() { return _q.size() >= _cap; }
    bool IsEmpty() { return _q.empty(); }
public:
    BlockQueue(int cap = defaultcap)
        : _cap(cap), _csleep_num(0), _psleep_num(0) {}

    void Equeue(const T &in)
    {
        LockGuard lockguard(_lock);
        // 生产者调用
        while(IsFull())
        {
            //生产者等待
            //重点1:pthread_cond_wait调用成功,挂起线程前要先自动释放锁
            //重点2:当线程被唤醒的时候,默认在临界区内唤醒,成功返回,需要当前线程重新申请锁
            //重点3:如果被唤醒但是申请失败了,我就会在锁上阻塞等待
            _psleep_num++;
            std::cout << "生产者休眠" << std::endl;
            _full_cond.Wait(_lock);
            _psleep_num--;
        }
        _q.push(in);

        if(_csleep_num)                               
        {
            _empty_cond.Siganl();
            std::cout << "唤醒消费者" << std::endl;
        }
    }

    T Pop()
    {
        // 消费者调用
        LockGuard lockguard(_lock);
        while(IsEmpty())
        {
            _csleep_num++;
            std::cout << "消费者休眠" << std::endl;
            _empty_cond.Wait(_lock);
            _csleep_num--;
        }
        T data = _q.front();
        _q.pop();

        if(_psleep_num)
        {
            _full_cond.Siganl();
            std::cout << "唤醒生产者" << std::endl;
        }    
    
        return data;
    }

    ~BlockQueue() {}

private:
    std::queue<T> _q;
    int _cap; // 容量

    Mutex _lock;
    Cond _full_cond;
    Cond _empty_cond;

    int _csleep_num; // 消费者休眠个数
    int _psleep_num; // 生产者休眠个数
};